const ctxPath = document.getElementById("ctxPath").value;

const link = document.createElement('link');
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = ctxPath+"/templatesJs/util/NetworkPacketsParsing.css";
// 将 link 标签插入到 <head> 中
document.head.appendChild(link);

const script = document.createElement('script');
script.src = ctxPath+ "/static/js/xml2json.js";
script.type = "text/javascript";
document.head.appendChild(script);

export default {
    template: `
        <div class="wireshark-like-ui">
        <div class="packet-details-and-bytes">
          <el-collapse v-model="activeName" >
            <el-collapse-item title="原始信令" name="bytes" class="collapse-custom-item-1">
              <div class="packet-bytes">
                <div style="height: 7vh;overflow-y: auto" class="scrollable-container" @click="resetBackground">
              <span v-for="item in posValues"
                    @click.stop="selectItem(item[0])"
                    :style="{ backgroundColor: selectedIndex === item[0] ? 'yellow' : 'transparent' }">
                    {{ item[1].match(/.{1,2}/g).join(' ') }}
              </span>
                </div>
              </div>
            </el-collapse-item>
          </el-collapse>
          <div class="packet-details">
            <div style="height: 15vh;overflow-y: auto">
              <el-tree :data="protos" :props="defaultProps" :expand-on-click-node="true" node-key="id"
                       @node-click="handleNodeClick" :highlight-current="true"
                       :current-node-key="currentNodeId" ref="tree" class="custom-tree-highlight">
              </el-tree>
            </div>
          </div>
        </div>
      </div>
    `,
    props: {
        type: {
            type: String,
            default: null
        },
        src: {
            type: String,
            default: null
        },
    },
    data() {
        return {
            protos: [],
            xml:"",
            defaultProps: {
                children: 'field',
                label: (data) => {
                    return data._showname || data._show;
                }
            },
            posValues:undefined,
            selectedIndex: -1, // 初始化时没有选中任何项
            currentNodeId: null, // 用于存储当前选中的节点ID
            activeName:"bytes",
            url:"http://192.168.0.137:7808/process"
        };
    },
    watch:{
        src: {
            immediate: true,
            handler(val) {
                this.getXmlStr();
            }
        },
    },
    methods: {
        // 递归处理 field 对象
        processFieldObjects(proto) {
            if (proto.field) {
                if (Array.isArray(proto.field)) {
                    // 如果 field 是数组，直接迭代
                    for (let field of proto.field) {
                        this.processFieldObjects(field);
                    }
                } else {
                    // 如果 field 是对象，将其转换为数组并迭代
                    proto.field = [proto.field];
                    for (let field of proto.field) {
                        this.processFieldObjects(field);
                    }
                }
                proto.id = proto._name+proto._showname+proto._show;
            }
        },
        parsePDML() {
            this.protos = [];
            var x2js = new X2JS();
            var jsonObj = x2js.xml_str2json( this.xml );
            if (Array.isArray(jsonObj.pdml.packet)) {
                for (let i in jsonObj.pdml.packet[0].proto) {
                    if (i != 0 && jsonObj.pdml.packet[0].proto[i]._name != 'fake-field-wrapper') {
                        this.processFieldObjects(jsonObj.pdml.packet[0].proto[i]);
                        this.protos.push(jsonObj.pdml.packet[0].proto[i])
                    }
                }
            } else {
                for (let i in jsonObj.pdml.packet.proto) {
                    if (i != 0 && jsonObj.pdml.packet.proto[i]._name != 'fake-field-wrapper') {
                        this.processFieldObjects(jsonObj.pdml.packet.proto[i]);
                        this.protos.push(jsonObj.pdml.packet.proto[i])
                    }
                }
            }

            // 遍历JSON数据中的每个对象
            this.posValues = new Map();
            this.protos.forEach(item => {
                // 检查对象中是否包含'field'属性
                if (item.field) {
                    item.field.forEach(field => {
                        if (field._value) {
                            let val = field._unmaskedvalue != undefined ? field._unmaskedvalue : field._value;
                            this.posValues.set(field._pos, val);
                        }
                    });
                }
            });
        },
        handleNodeClick(data, node) {
            this.selectedIndex = data._pos;
        },
        expandNodeByIndex(id) {
            // 获取指定索引的节点
            const node = this.$refs.tree.getNode(id);
            if (node) {
                // 展开或折叠节点
                if (node.level > 0) { // 确保不是根节点
                    node.parent.expanded = true;
                }
                node.expanded = true;
            }
            // 设置当前选中的节点ID
            this.currentNodeId = id;
            this.$refs.tree.setCurrentKey(id);
        },
        selectItem(index) {
            this.selectedIndex = index; // 更新选中索引
            const findNestedProperty = (data, targetProp, targetValue) => {
                return data.reduce((acc, item) => {
                    if (item[targetProp] === targetValue) {
                        acc.push(item);
                    }
                    if (item.field) {
                        const nestedResult = findNestedProperty(item.field, targetProp, targetValue);
                        if (nestedResult.length > 0) {
                            acc.push(...nestedResult);
                        }
                    }
                    return acc;
                }, []);
            };
            const result = findNestedProperty(this.protos, '_pos', index);
            if(result.length >0){
                let idObect = result[0];
                this.expandNodeByIndex(idObect._name+idObect._showname+idObect._show)
            }

        },
        resetBackground(){
            if (this.selectedIndex !== -1) {
                this.selectedIndex = -1; // 如果点击了空白区域，则取消选中
            }

        },
        getXmlStr() {
            // fr(26-gb), ethernet(1), hdlc(200), lapd(131-abis), linuxlapd(88-abis), mtp2(42-a)
            let postData = {}
            let type = 0;
            if(this.type != null){
                switch (this.type){
                    case "abis":
                        type = 131;
                        break;
                    case "a":
                        type = 42;
                        break;
                    case "pri":
                        type = 200;
                        break;
                    default:
                        type = 0;
                }
                if(type !== 0){
                    postData.type = type;
                }
            }
            if(this.src != null){
                postData.src = this.src;
            }
            const settings = {
                "url": this.url,
                "method": "POST",
                "timeout": 0,
                "headers": {
                    "Content-Type": "application/json"
                },
                "data": JSON.stringify(postData),
            };

            $.ajax(settings).done((response) => {
                this.xml = response;
                console.log("xml",this.xml)
                if(this.xml != null || this.xml !== ""){
                    this.parsePDML();
                    console.log("parsePDML",this.xml)
                }else{
                    console.log("xml is null")
                }
                return true;
            });
        }
    },
    mounted() {},
};